﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace webSocketServer
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        public Socket socketwatch = null;

        //客户端连接集合
        public static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };

        private void button1_Click(object sender, EventArgs e)
        {
            int port = 10;

            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
            socketwatch = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socketwatch.NoDelay = false;
            socketwatch.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, true);
            socketwatch.ReceiveTimeout = 50 * 1000;

            try
            {
                socketwatch.Bind(localEP);
                socketwatch.Listen(10);

                Thread thread = new Thread(wacthconnecting);

                thread.IsBackground = true;
                thread.Start();
                appendText("开启监听");

            }
            catch (Exception ex)
            {
                appendText(ex.ToString() + "\n\r" + ex.Message);
            }
        }

        public void wacthconnecting()
        {
            Socket conn = null;
            while (true)
            {
                try
                {
                    conn = socketwatch.Accept();
                }
                catch (Exception ex)
                {
                    appendText(ex.Message + "\n\r" + ex.StackTrace);
                    break;
                }
                try
                {
                    //获取客户端的ip和端口号
                    //IPAddress clientIP = (conn.RemoteEndPoint as IPEndPoint).Address;
                    //int clientPort = (conn.RemoteEndPoint as IPEndPoint).Port;

                    //客户端网络节点号
                    string remoteEndPointStr = conn.RemoteEndPoint.ToString();

                    //添加客户端信息
                    clientConnectionItems.Add(remoteEndPointStr, conn);
                    appendText(string.Format("成功与{0}客户端建立连接", remoteEndPointStr));
                    appendText(string.Format("当前在线客户端统计：{0}", clientConnectionItems.Count));

                    AddOnlineItem(remoteEndPointStr);

                    IPEndPoint netPoint = conn.RemoteEndPoint as IPEndPoint;

                    //创建一个通信线程
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(Recv);
                    Thread thread = new Thread(pts);
                    //设置为后台线程，UI主线程退出就都退出了
                    thread.IsBackground = true;
                    thread.Start(conn);
                }
                catch (Exception ex)
                {
                    appendText(ex.Message + "\n\r" + ex.StackTrace);
                    //CSHelper.saveErrLog(ex.Message + "\n\r" + ex.StackTrace, "log");
                }
            }
        }

        public void Recv(object socketClientPara)
        {
            Socket sc = socketClientPara as Socket;
            string clientIp = sc.RemoteEndPoint.ToString();
            //握手
            int RecvByteLen = 0; byte[] buffer = new byte[1024];
            RecvByteLen = sc.Receive(buffer);//接受客户端握手信息
            sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer, RecvByteLen)));
            appendText("发送握手协议给:" + sc.RemoteEndPoint);
            while (true)
            {
                try
                {
                    if (sc != null)
                    {
                        //接受客户端数据
                        RecvByteLen = sc.Receive(buffer);//接受客户端握手信息
                        if (RecvByteLen == 0)
                        {
                            continue;
                        }
                        else
                        {
                            //解析客户端的数据
                            string clientMsg = AnalyticData(buffer, RecvByteLen);
                            appendText("接受到" + sc.RemoteEndPoint + "客户端数据：" + clientMsg);
                        }

                        //recvAll = recvBuf;
                        appendText(string.Format("RecvByte:{0} from{1}", RecvByteLen, clientIp));
                    }
                }
                catch (Exception ex)
                {
                    //移出列表
                    clientConnectionItems.Remove(sc.RemoteEndPoint.ToString());
                    appendText("客户端" + sc.RemoteEndPoint + "已经中断连接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n");
                    appendText(string.Format("当前在线客户端统计：{0}", clientConnectionItems.Count));
                    RemoveOnlineItem(sc.RemoteEndPoint.ToString());

                    //如果发生错误，忽略，重新搞个循环
                    sc.Close();
                    break;
                }
                finally
                {
                    Thread.Sleep(3000);
                }
            }
        }

        /// <summary>
        /// 打包握手信息
        /// </summary>
        /// <param name="secKeyAccept"></param>
        /// <returns></returns>
        private static byte[] PackHandShakeData(string secKeyAccept)
        {
            var responseBuilder = new StringBuilder();
            responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);
            responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);
            responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);
            responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);
            //如果把上一行换成下面两行，才是thewebsocketprotocol-17协议，但居然握手不成功，目前仍没弄明白！
            //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);
            //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);

            return Encoding.UTF8.GetBytes(responseBuilder.ToString());
        }

        /// <summary>
        /// 生成Sec-WebSocket-Accept
        /// </summary>
        /// <param name="handShakeText">客户端握手信息</param>
        /// <returns>Sec-WebSocket-Accept</returns>
        private static string GetSecKeyAccetp(byte[] handShakeBytes, int bytesLength)
        {
            string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);
            string key = string.Empty;
            Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
            Match m = r.Match(handShakeText);
            if (m.Groups.Count != 0)
            {
                key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
            }
            byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
            return Convert.ToBase64String(encryptionString);
        }

        /// <summary>
        /// 解析客户端数据包
        /// </summary>
        /// <param name="recBytes">服务器接收的数据包</param>
        /// <param name="recByteLength">有效数据长度</param>
        /// <returns></returns>
        private static string AnalyticData(byte[] recBytes, int recByteLength)
        {
            if (recByteLength < 2) { return string.Empty; }

            bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit，1表示最后一帧  
            if (!fin)
            {
                return string.Empty;// 超过一帧暂不处理 
            }

            bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩码  
            if (!mask_flag)
            {
                return string.Empty;// 不包含掩码的暂不处理
            }

            int payload_len = recBytes[1] & 0x7F; // 数据长度  

            byte[] masks = new byte[4];
            byte[] payload_data;

            if (payload_len == 126)
            {
                Array.Copy(recBytes, 4, masks, 0, 4);
                payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 8, payload_data, 0, payload_len);

            }
            else if (payload_len == 127)
            {
                Array.Copy(recBytes, 10, masks, 0, 4);
                byte[] uInt64Bytes = new byte[8];
                for (int i = 0; i < 8; i++)
                {
                    uInt64Bytes[i] = recBytes[9 - i];
                }
                UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0);

                payload_data = new byte[len];
                for (UInt64 i = 0; i < len; i++)
                {
                    payload_data[i] = recBytes[i + 14];
                }
            }
            else
            {
                Array.Copy(recBytes, 2, masks, 0, 4);
                payload_data = new byte[payload_len];
                Array.Copy(recBytes, 6, payload_data, 0, payload_len);

            }

            for (var i = 0; i < payload_len; i++)
            {
                payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]);
            }

            return Encoding.UTF8.GetString(payload_data);
        }


        /// <summary>
        /// 打包服务器数据
        /// </summary>
        /// <param name="message">数据</param>
        /// <returns>数据包</returns>
        private static byte[] PackData(string message)
        {
            byte[] contentBytes = null;
            byte[] temp = Encoding.UTF8.GetBytes(message);

            if (temp.Length < 126)
            {
                contentBytes = new byte[temp.Length + 2];
                contentBytes[0] = 0x81;
                contentBytes[1] = (byte)temp.Length;
                Array.Copy(temp, 0, contentBytes, 2, temp.Length);
            }
            else if (temp.Length < 0xFFFF)
            {
                contentBytes = new byte[temp.Length + 4];
                contentBytes[0] = 0x81;
                contentBytes[1] = 126;
                contentBytes[2] = (byte)(temp.Length & 0xFF);
                contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);
                Array.Copy(temp, 0, contentBytes, 4, temp.Length);
            }
            else
            {
                // 暂不处理超长内容  
            }

            return contentBytes;
        }

        public string lastLogText = "";
        /// <summary>
        /// 添加到日志
        /// </summary>
        /// <param name="log">日志信息</param>
        private void appendText(string log, bool save = true)
        {
            Action<string> actionDelegate = (x) =>
            {
                if (this.richTextBox1.Text.Length > 20000)
                {
                    this.richTextBox1.Text = this.richTextBox1.Text.Substring(20000, this.richTextBox1.Text.Length - 20000);
                }
                this.richTextBox1.AppendText(DateTime.Now.ToString() + ":" + log);
                richTextBox1.AppendText(System.Environment.NewLine);
                this.richTextBox1.ScrollToCaret();
            };
            this.richTextBox1.Invoke(actionDelegate, log);
            //CSHelper.saveErrLog(log, "report");
        }

        /// <summary>
        /// 添加上线的指静脉设备
        /// </summary>
        /// <param name="itemName"></param>
        private void AddOnlineItem(string itemName)
        {
            Action<string> actionDelegate = (x) =>
            {
                this.clbOnlineClient.Items.Add(itemName);
            };
            this.clbOnlineClient.Invoke(actionDelegate, itemName);
        }
        /// <summary>
        /// 移出下线的指静脉设备
        /// </summary>
        /// <param name="itemName"></param>
        private void RemoveOnlineItem(string itemName)
        {
            Action<string> actionDelegate = (x) =>
            {
                this.clbOnlineClient.Items.Remove(itemName);
            };
            this.clbOnlineClient.Invoke(actionDelegate, itemName);
        }

        private void btnSendMsg2Clients_Click(object sender, EventArgs e)
        {
            foreach (Socket sc in clientConnectionItems.Values)
            {
                //客户端网络节点号
                string remoteEndPointStr = sc.RemoteEndPoint.ToString();
                try
                {
                    //发送数据
                    var sendMsg = txtFromServer.Text.Trim();
                    appendText("发送数据：[" + sendMsg + "] 至客户端>>" + remoteEndPointStr);
                    sc.Send(PackData(sendMsg));
                }
                catch (Exception ex)
                {
                    appendText("发送失败。>>" + remoteEndPointStr + "\n\r" + ex.Message);
                }
            }
        }
    }
}
